package com.study.crypto.signer.pdf.signer;

import com.itextpdf.signatures.DigestAlgorithms;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.asn1.x509.Certificate;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;

/**
 * 使用外传摘要方式，进行 pdf RSA 签名
 * @author Songjin
 * @since 2022-03-30 17:46
 */
public class PdfPKCS7RSADeferredSigner extends PdfPKCS7DeferredSigner {
    
    public PdfPKCS7RSADeferredSigner(PrivateKey privateKey, Certificate certificate, byte[] digest) {
        super(privateKey, certificate, digest);
    }
    
    public PdfPKCS7RSADeferredSigner(PrivateKey privateKey, Certificate certificate, byte[] digest, String digestAlgo) {
        super(privateKey, certificate, digest);
        setDigestAlgo(digestAlgo);
    }
    
    @Override
    public byte[] signDeferred(String sigFieldName, byte[] toSignedBytes) throws GeneralSecurityException, IOException {
        if (StringUtils.isBlank(digestAlgo)) {
            // 如果未设置摘要算法名称，默认采用 sha256 算法
            setDigestAlgo(DigestAlgorithms.SHA256);
        }
        return super.signDeferred(sigFieldName, toSignedBytes);
    }
}
